package com.wzy.controller;

import com.wzy.pojo.SysRole;
import com.wzy.pojo.SysUser;
import com.wzy.service.SysRoleService;
import com.wzy.service.SysUserService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @auth wzy
 * @date 2023/11/4 10:47
 */
@Controller
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping("/list")
    public String list(Model model, Integer roleId, String realName, @RequestParam(value ="pageIndex",defaultValue = "1") Integer pageIndex) {
        SysUser sysUser = new SysUser();
        sysUser.setRoleId(roleId);
        sysUser.setRealName(realName);
        // 页面大小
        Integer pageSize = 5;

        List<SysUser> list = sysUserService.selectSysUserList(sysUser, pageIndex, pageSize);
        model.addAttribute("userList", list);

        List<SysRole> roleList = sysRoleService.getRoleList();
        model.addAttribute("roleList", roleList);

        model.addAttribute("roleId", roleId);
        model.addAttribute("realName", realName);


//        totalCount 总记录数
        Integer totalCount = sysUserService.selectCount(sysUser);

        //totalPageCount 总页数
        Integer totalPageCount = totalCount / pageSize;
        if (totalCount % pageSize != 0) {
            totalPageCount++;
        }

        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);

//        currentPageNo 当前页码
        model.addAttribute("currentPageNo", pageIndex);

        return "/sysUser/list";
    }


    @GetMapping("/toAdd")
    public String toAdd(Model model) {

        List<SysRole> roleList = sysRoleService.getRoleList();
        model.addAttribute("roleList", roleList);

        return "/sysUser/add";
    }

    @PostMapping("/add")
    public String add(Model model, HttpServletRequest request, @Valid SysUser sysUser, BindingResult bindingResult
                      , @RequestParam(required = false) MultipartFile idPic) throws IOException {

        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();

            for (FieldError fieldError : fieldErrors) {
                model.addAttribute(fieldError.getField()+"Error",fieldError.getDefaultMessage());
            }


            model.addAttribute("sysUser",sysUser);
            return "/sysUser/add";
        }

        model.addAttribute("sysUser",sysUser);
        if (!idPic.isEmpty()){
            // 文件上传
            if (idPic.getSize()>500000){
                model.addAttribute("idPicError","文件过大，不能上传");
                return "/sysUser/add";
            }

            // 自定义 文件名  abc.jpg
            String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));

            if (".jpg.png".indexOf(suffix)==-1){
                model.addAttribute("idPicError","文件格式不正确，不能上传");
                return "/sysUser/add";
            }

            // 指定文件存储的目录
            String path = request.getSession().getServletContext().getRealPath("statics")+File.separator+"upload";  //

            String fileName = RandomUtils.nextInt(1000000)+"_pic"+suffix;

            File targetFile = new File(path+File.separator+fileName);
            //如果文件不存在就创建
            if (!targetFile.exists()){
                targetFile.mkdirs();
            }
            // 核心代码，文件传输
            idPic.transferTo(targetFile);

            sysUser.setIdPicPath(fileName);
        }


        int result = sysUserService.add(sysUser);

        if (result>0){
            return "redirect:/sys/user/list";
        }


        return "/sysUser/add";


    }

    @GetMapping("/view/{id}")
    public String view(Model model, @PathVariable Integer id){

        SysUser sysUser = sysUserService.selectById(id);

        model.addAttribute("sysUser",sysUser);

        return "/sysUser/view";
    }

    @ResponseBody
    @GetMapping(value = "/viewAjax/{id}")
    public Object viewAjax(@PathVariable Integer id){

        SysUser sysUser = sysUserService.selectById(id);

//        String jsonString = JSON.toJSONString(sysUser);

        return sysUser;
    }


    @GetMapping("/toUpdate")
    public String toUpdate(Model model, Integer uid) {

        SysUser sysUser = sysUserService.selectById(uid);

        model.addAttribute("sysUser",sysUser);

        List<SysRole> roleList = sysRoleService.getRoleList();
        model.addAttribute("roleList", roleList);

        return "/sysUser/update";
    }

    @PostMapping("/update")
    public String update(Model model, SysUser sysUser){

        int result = sysUserService.update(sysUser);

        if (result>0){
            return "redirect:/sys/user/list";
        }

        model.addAttribute("sysUser",sysUser);
        return "/sysUser/update";


    }

    @ResponseBody
    @GetMapping("/userExist")
    public String userExist(String account){

        SysUser sysUser = sysUserService.selectByAccount(account);

        // {"name":"张三","age":18}  [{},{]

        if (sysUser==null){
            // 不存在  {"exist":0}
            return "{\"exist\":0}";
        }

        // 存在
        return "{\"exist\":1}";
    }
}